#ifndef __QTCH_FIBER_H__
#define __QTCH_FIBER_H__

#include <ucontext.h>
#include <memory>
#include <functional>

namespace qtch{


class Fiber : public std::enable_shared_from_this<Fiber>{
public:
    typedef std::shared_ptr<Fiber> ptr;


    enum State{
        /// 初始化状态
        INIT,
        /// 暂停状态
        HOLD,
        /// 执行中状态
        EXEC,
        /// 结束状态
        TERM,
        /// 可执行状态
        READY,
        /// 异常状态
        EXCEPT
    };

    Fiber(std::function<void()> cb, size_t stackSize = 0);
    Fiber();
    ~Fiber();
    void swapIn();
    void swapOut();
    void reset(std::function<void()> cb);
    static void yieldToHold();
    static void yieldToReady();
    uint64_t getId() const{ return m_id;}
    static uint64_t getFiberId();
    State getState() const{ return m_state;}
    static void SetThis(Fiber::ptr fiber);
    static Fiber::ptr GetThis();
    static void MainFun();

    static uint64_t getFibersCount();

private:
    uint64_t m_id;
    uint32_t m_stackSize = 0;
    State m_state = INIT; 
    ucontext_t m_ctx;
    void *m_stack = nullptr;
    std::function<void()> m_cb;
};













}


#endif